package icu.sunway.gushenBlogBackEnd.Service.Implement;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import icu.sunway.gushenBlogBackEnd.Configuration.OssConfig;
import icu.sunway.gushenBlogBackEnd.Entity.View.ResultVO;
import icu.sunway.gushenBlogBackEnd.Service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    private final OssConfig ossConfig;

    FileServiceImpl(OssConfig ossConfig) {
        this.ossConfig = ossConfig;
    }

    @Override
    public ResultVO<String> upload(MultipartFile file, String folder) {
        //获取相关配置
        String bucketName = ossConfig.getBucketName();
        String endPoint = ossConfig.getEndPoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        //获取原生文件名
        String originalFilename = file.getOriginalFilename();

        //拼装OSS上存储的路径
        String fileName = generateUUID();
        String extension = null;
        if (originalFilename != null) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        //在OSS上bucket下的文件名
        String uploadFileName = folder + "/" + fileName + extension;

        // 返回路径
        String accessURL = null;
        try {
            PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, file.getInputStream());
            //拼装返回路径
            if (result != null) {
                accessURL = "https://" + bucketName + "." + endPoint + "/" + uploadFileName;
            }
        } catch (Exception e) {
            return new ResultVO<>(400, "上传文件失败", null);
        } finally {
            //OSS关闭服务，不然会造成OOM
            ossClient.shutdown();
        }
        return new ResultVO<>(200, "上传文件成功", accessURL);
    }

    /**
     * 获取随机字符串
     */
    private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }
}
